<?php
use Symfony\Component\Yaml\Yaml;
class TbfEncoding{
    static function AjkError($str){
        echo json_encode(array('err'=>$str));
        return null;
    }
    static function AjkSuccess($data=null){
        echo json_encode(array('err'=>'','data'=>$data));
        return null;
    }
    static function JsonEncode($data){
        return json_encode($data);
    }

    static function JsonEncodePretty($data){
        return json_encode($data,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
    }

    /**
     * 使用json_decode,并且把错误抛到exception里面的JsonDecode
     * @param string $str
     * @return object
     * @throws Exception
     */
    static function JsonDecode($str){
        $obj = json_decode($str,true);
        $error_code = json_last_error();
        if ($error_code==JSON_ERROR_NONE){
            return $obj;
        }
        throw new Exception('json_decode fail '.json_last_error_msg());
    }
    static function base64UrlEncode($s){
        $s = base64_encode($s);
        $s = strtr($s,array('+'=>'-','/'=>'_'));
        return rtrim($s,'=');

    }
    static function base64UrlDecode($s){
        $s = strtr($s,array('-'=>'+','_'=>'/'));
        $s = str_pad($s,strlen($s)%4,'=',STR_PAD_RIGHT);
        return base64_decode($s,true);
    }
    static function readJsonFile($path){
        $content = file_get_contents($path);
        return json_decode($content,true);
    }
    static function writeJsonToFilePretty($path,$data){
        $content = json_encode($data,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
        file_put_contents($path,$content);
    }
    static function readYamlFile($path){
        $content = file_get_contents($path);
        return Yaml::parse($content);
    }
}
